package org.server.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @className: RedisUtil
 * @description:
 * @author: sh.Liu
 * @date: 2022-03-09 14:07
 */
@Slf4j
@Component
@Scope("prototype")
public class RedisUtil {

    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private HashOperations<Object, Object, Object> hashOperations;

    /**
     * 给一个指定的 key 值附加过期时间
     *
     * @param key
     * @param time
     * @return
     */
    public boolean expire(String key, long time) {
        return Boolean.TRUE.equals(redisTemplate.expire(key, time, TimeUnit.SECONDS));
    }

    /**
     * 根据key 获取过期时间
     *
     * @param key
     * @return
     */
    public long getTime(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 根据key 获取过期时间
     *
     * @param key
     * @return
     */
    public boolean hasKey(String key) {
        return Boolean.TRUE.equals(redisTemplate.hasKey(key));
    }

    /**
     * 移除指定key 的过期时间
     *
     * @param key
     * @return
     */
    public boolean persist(String key) {
        return Boolean.TRUE.equals(redisTemplate.boundValueOps(key).persist());
    }

    /**
     * 增添hash操作
     * @param name
     * @param hk
     * @param hv
     * @return void
     * @author Tang
     * @date 2023/3/2 16:34
    **/
    public void setHash(Object name,Object hk,Object hv) {
        hashOperations.put(name,hk,hv);
    }

    /**
     * 批量获取hash中的值
     * @param name
     * @param hk
     * @return java.util.List<java.lang.Object>
     * @author Tang
     * @date 2023/3/2 22:02
    **/
    public List<Object> getValuesInHash(Object name, Collection<Object> hk) {
        return hashOperations.multiGet(name, hk);
    }

    /**
     * 获取hash中的值
     * @param name
     * @param hk
     * @return java.lang.Object
     * @author Tang
     * @date 2023/3/28 23:00
    **/
    public Object getValueInHash(Object name,Object hk) {
        return hashOperations.get(name,hk);
    }

    public void removeValueInHash(Object name,Object hk) {
        hashOperations.delete(name,hk);
    }

    public boolean isExistHash(Object name) {
        Long expire = redisTemplate.getExpire(name);
        return expire != null && expire != -2L;
    }

    /**
     * 根据key删除对应的hash
     * @param name
     * @return void
     * @author Tang
     * @date 2023/3/28 23:53
    **/
    public void removeHash(Object name){
        redisTemplate.delete(name);
    }
}
